package org.uni_hi.lsep.gui.util;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.DefaultComboBoxModel;
import javax.swing.InputVerifier;
import javax.swing.JComboBox;
import javax.swing.JTextField;

public class VerifiedTextField extends JComboBox {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1692985347486486299L;

	public VerifiedTextField() {
		this(new Object[8]);
	}

	public VerifiedTextField(Object[] vals) {
		super(vals);
		setEditor(new VTFEditor());
		setEditable(true);
		setModel(new DefaultComboBoxModel());
		addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				transferFocus();
			}
		});
		addFocusListener(new FocusListener() {

			@Override
			public void focusLost(FocusEvent e) {
			}

			@Override
			public void focusGained(FocusEvent e) {
				getEditor().selectAll();
				showPopup();
			}
		});
		addPopupMenuListener(new ComboPopupMenuListener());
		getModel();
	}

	public VTFEditor getEditor() {
		return (VTFEditor) super.getEditor();
	}

	public boolean verify() {
		return getEditor().verify();
	}

	public void setInputVerifier(InputVerifier iv) {
		// super.setInputVerifier(iv);
		((JTextField) getEditor().getEditorComponent()).setInputVerifier(iv);
	}

	public void setSelectedItem(Object obj) {
		if (((DefaultComboBoxModel) getModel()).getIndexOf(obj) == -1) {
			super.addItem(obj);
		}
		super.setSelectedItem(obj);
	}

	public void setName(String name) {
		super.setName(name);
		getEditor().getEditorComponent().setName(name);
	}

	public void setBackground(Color color) {
		super.setBackground(color);
		if (getEditor() != null) {
			getEditor().getEditorComponent().setBackground(color);
		}
	}
}
